package com.smart.translator.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.smart.translator.data.User;
import org.json.JSONObject;

/**
 * 用户管理工具类
 */
public class UserManager {
    private static final String TAG = "UserManager";
    private static final String PREF_NAME = "user_preferences";
    private static final String KEY_USER = "current_user";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";
    
    private static UserManager instance;
    private SharedPreferences preferences;
    private User currentUser;
    private boolean isLoggedIn = false;

    private UserManager(Context context) {
        preferences = context.getApplicationContext()
                .getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        loadUserFromPreferences();
    }

    public static synchronized UserManager getInstance(Context context) {
        if (instance == null) {
            instance = new UserManager(context);
        }
        return instance;
    }

    /**
     * 保存用户信息
     */
    public void saveUser(User user) {
        this.currentUser = user;
        this.isLoggedIn = true;
        
        try {
            JSONObject userJson = new JSONObject();
            userJson.put("id", user.getId());
            userJson.put("username", user.getUsername());
            userJson.put("phone", user.getPhone());
            userJson.put("email", user.getEmail());
            userJson.put("message", user.getMessage());
            
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(KEY_USER, userJson.toString());
            editor.putBoolean(KEY_IS_LOGGED_IN, true);
            editor.apply();
            
            Log.d(TAG, "用户信息已保存: " + user.getUsername());
        } catch (Exception e) {
            Log.e(TAG, "保存用户信息失败", e);
        }
    }

    /**
     * 从本地存储加载用户信息
     */
    private void loadUserFromPreferences() {
        try {
            String userJsonStr = preferences.getString(KEY_USER, null);
            isLoggedIn = preferences.getBoolean(KEY_IS_LOGGED_IN, false);
            
            if (userJsonStr != null && isLoggedIn) {
                JSONObject userJson = new JSONObject(userJsonStr);
                currentUser = new User();
                currentUser.setId(userJson.optInt("id", 0));
                currentUser.setUsername(userJson.optString("username", ""));
                currentUser.setPhone(userJson.optString("phone", ""));
                currentUser.setEmail(userJson.optString("email", ""));
                currentUser.setMessage(userJson.optString("message", ""));
                
                Log.d(TAG, "用户信息已加载: " + currentUser.getUsername());
            }
        } catch (Exception e) {
            Log.e(TAG, "加载用户信息失败", e);
            clearUser();
        }
    }

    /**
     * 获取当前用户
     */
    public User getCurrentUser() {
        return currentUser;
    }

    /**
     * 检查是否已登录
     */
    public boolean isLoggedIn() {
        return isLoggedIn && currentUser != null;
    }

    /**
     * 退出登录
     */
    public void logout() {
        this.currentUser = null;
        this.isLoggedIn = false;
        
        SharedPreferences.Editor editor = preferences.edit();
        editor.remove(KEY_USER);
        editor.putBoolean(KEY_IS_LOGGED_IN, false);
        editor.apply();
        
        Log.d(TAG, "用户已退出登录");
    }

    /**
     * 清除用户信息
     */
    private void clearUser() {
        this.currentUser = null;
        this.isLoggedIn = false;
        
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.apply();
        
        Log.d(TAG, "用户信息已清除");
    }

    /**
     * 获取用户名显示
     */
    public String getDisplayName() {
        if (currentUser != null) {
            if (currentUser.getUsername() != null && !currentUser.getUsername().isEmpty()) {
                return currentUser.getUsername();
            } else if (currentUser.getPhone() != null && !currentUser.getPhone().isEmpty()) {
                return currentUser.getPhone();
            } else if (currentUser.getEmail() != null && !currentUser.getEmail().isEmpty()) {
                return currentUser.getEmail();
            }
        }
        return "未登录";
    }

    /**
     * 获取用户ID
     */
    public int getUserId() {
        return currentUser != null ? currentUser.getId() : 0;
    }

    /**
     * 检查用户ID是否有效
     */
    public boolean hasValidUserId() {
        return currentUser != null && currentUser.getId() > 0;
    }
} 